﻿/************************************************************************

   Extended Silverlight Toolkit

   Copyright (C) 2010-2012 Xceed Software Inc.

   This program is provided to you under the terms of the Microsoft Public
   License (Ms-PL) as published at http://extendedsilverlight.codeplex.com/license

   Please purchase a commercial version of this toolkit if you are using
   it in a commercial product. The commercial versions support the project,
   and also include more features for each control, priority support,
   source code, updates, removed watermark, and a proprietary license.

   Visit http://xceed.com and follow @datagrid on Twitter.

  **********************************************************************/

using System;
using System.Threading;

namespace Xceed.Silverlight.Data
{
  internal class CustomAsyncResult : AsyncResultBase, IDisposable
  {
    internal CustomAsyncResult( Guid callId, object asyncState )
      : base( callId )
    {
      m_asyncState = asyncState;
    }

    public override object AsyncState
    {
      get
      {
        return m_asyncState;
      }
    }

    public override WaitHandle AsyncWaitHandle
    {
      get
      {
        if( m_waitHandle == null )
        {
          m_waitHandle = new ManualResetEvent( this.IsCompleted );
        }
        return m_waitHandle;
      }
    }

    public override bool CompletedSynchronously
    {
      get
      {
        return m_completedSynchronously;
      }
    }

    public override bool IsCompleted
    {
      get
      {
        return m_isCompleted;
      }
    }

    public virtual void Complete( bool synchronously, bool setWaitHandle )
    {
      m_isCompleted = true;
      m_completedSynchronously = synchronously;
      if( setWaitHandle )
      {
        this.SetWaitHandle();
      }
    }

    internal void SetWaitHandle()
    {
      if( m_waitHandle != null )
      {
        m_waitHandle.Set();
      }
    }


    #region IDisposable Members

    public void Dispose()
    {
      this.Dispose( true );
      GC.SuppressFinalize( this );
    }

    private bool m_disposed;//false;

    protected virtual void Dispose( bool disposing )
    {
      if( !m_disposed )
      {
        if( disposing )
        {
          if( m_waitHandle != null )
          {
            ( ( IDisposable )m_waitHandle ).Dispose();
          }
        }
        m_disposed = true;
      }
    }

    #endregion IDisposable Members


    #region Private Fields

    private object m_asyncState; // null;
    private bool m_completedSynchronously; // false;
    private bool m_isCompleted; // false;
    private ManualResetEvent m_waitHandle; //null;

    #endregion Private Fields
  }
}
